package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.dubbo.api.mongo.FriendApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {

//        判断表中是否已经有数据  select * from friend where userId=?? and friendId=??

        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));

        if(!mongoTemplate.exists(query,Friend.class)){
            Friend friend = new Friend();
            friend.setId(new ObjectId());
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(new Date().getTime());
            mongoTemplate.save(friend);
        }


        Query query1 = new Query(Criteria.where("friendId").is(userId).and("userId").is(friendId));
        if(!mongoTemplate.exists(query1,Friend.class)) {
            Friend friend1 = new Friend();
            friend1.setId(new ObjectId());
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(new Date().getTime());
            mongoTemplate.save(friend1);
        }
    }

    @Override
    public void deleteFriend(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(uid));
        mongoTemplate.remove(query);
        Query query1 = new Query(Criteria.where("userId").is(uid).and("friendId").is(userId));
        mongoTemplate.remove(query1);
    }
}
